package com.ruoyi.contract.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;

import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.contract.annotation.enums.ConBusinessOperType;
import com.ruoyi.contract.domain.ConObjOut;
import com.ruoyi.contract.domain.vo.ObjOutParam;
import com.ruoyi.contract.service.IConBusinessService;
import com.ruoyi.contract.service.IConObjOutService;
import com.ruoyi.contract.service.IConOperLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by zhangxiang on 2021/9/26.
 */
@RestController
@RequestMapping("/conobj")
public class ConObjController {

    @Autowired
    IConObjOutService conObjOutService;

    @Autowired
    IConBusinessService conBusinessService;

    @Autowired
    IConOperLogService conOperLogService;
    
    

    /**
     * 获取外部关系对象
     */
    @GetMapping("/outlist/{conId}")
    public AjaxResult listOutObject(@PathVariable("conId")Long conId){
        return AjaxResult.success(conObjOutService.listConObjOutByConId(conId));
    }


    /**
     * 删除外部关系对象
     */
    @PutMapping("/delo")
    @Log(title = "删除外部关系对象", businessType = BusinessType.DELETE)
    public AjaxResult delOutObject(@RequestBody List<ConObjOut> conObjOutList){
        if(!conBusinessService.operateAble(conObjOutList.get(0).getConId())){
            return AjaxResult.error("已冻结或作废无法操作！");
        }
        for (ConObjOut conObjOut : conObjOutList){
            conObjOutService.remove(new QueryWrapper<ConObjOut>().lambda().eq(ConObjOut::getConId,conObjOut.getConId()).eq(ConObjOut::getCustomerGkey,conObjOut.getCustomerGkey()));
        }
        return AjaxResult.success("删除成功！");
    }


    /**
     * 新增外部关系对象
     */
    @PostMapping("/addOut")
    @Log(title = "新增外部关系对象", businessType = BusinessType.INSERT)
    public AjaxResult addOutObject(@RequestBody ObjOutParam objOutParam){
        Long conId = objOutParam.getConId();
        if(!conBusinessService.operateAble(conId)){
            return AjaxResult.error("已冻结或作废无法操作！");
        }
        if(conId==null){
            return AjaxResult.error("请创建合同后再新增合tring同对象！");
        }
        for(String cusId : objOutParam.getCustomerGkey()){
            ConObjOut conObjOut = new ConObjOut();
            conObjOut.setCustomerGkey(cusId);
            conObjOut.setConId(conId);
            conObjOutService.saveOrUpdate(conObjOut,new QueryWrapper<ConObjOut>().lambda().eq(ConObjOut::getCustomerGkey,cusId).eq(ConObjOut::getConId,conId));
        }
        conOperLogService.saveConOperLog(conId, ConBusinessOperType.ADD_OUT.getName(),null);
        return AjaxResult.success();
    }
}
